package com.gasolinator.a.util;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import com.gasolinator.a.R;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class AssetsUtil {

    //TODO: crear paquete dinámico


    private static void createFileFromAssets(Context context, String assets, String destination) throws IOException {

        InputStream is = context.getAssets().open(assets);

        FileOutputStream fos = new FileOutputStream(destination);
        byte buf[] = new byte[1024];
        int len;
        while ((len = is.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }
        fos.close();

    }

    public static void createDatabaseFile(Context context) {
        try {
            final String databaseFolder = "/data/data/com.gasolinator.a/databases/";
            File myNewFolder = new File(databaseFolder);
            myNewFolder.mkdir();
//            createFileFromAssets(context, "gaswalker.db", databaseFolder + "gaswalker.db");
            unzipDatabase(context,"/data/data/com.gasolinator.a/databases/gaswalker.db");
        }
        catch (IOException e) {
            Log.e("ERROR IN createDatabaseFile ", e.getStackTrace().toString());
        }

    }

    private static void unzipDatabase(Context context, String databasePath) throws IOException {

        Resources t = context.getResources();
        InputStream fis = t.openRawResource(R.raw.gaswalker);
        if (fis == null) {
            return;
        }
        final int BUFFER = 8192;
        ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis,BUFFER));
        ZipEntry entry;
        while ((entry = zin.getNextEntry()) != null) {
            int count;

            FileOutputStream fos = new FileOutputStream(databasePath);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

            byte data[] = new byte[BUFFER];

            while ((count = zin.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
        zin.close();

    }


}